package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {

    @Override
    public ResponseResult listByName(ChannelDto dto) {

//        分页根据名称模糊查询
//        1、dto 为空
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE) ;
        }

//        QueryWrapper<WmChannel> queryWrapper = new QueryWrapper<>();
//        queryWrapper.like("name",dto.getName());
//        queryWrapper.lambda().like(WmChannel::getName,dto.getName());

        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(WmChannel::getName,dto.getName());

        IPage<WmChannel> page = new Page<>(dto.getPage(),dto.getSize());

        IPage<WmChannel> page1 = this.page(page, queryWrapper);

        return new PageResponseResult(dto.getPage(),dto.getSize(),page1.getTotal(),page1.getRecords());
//        Long currentPage当前页码, Integer size 每页显示条数, Long total 总记录数, T data 当前页的数据
    }

    @Override
    public ResponseResult saveChannel(WmChannel wmChannel) {

//        判断wmChannel是否为空  ，wmChannel的名称不能为空

        if(wmChannel==null|| StringUtils.isBlank( wmChannel.getName()) ){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
//        频道名称不能重复 ：判断即将新增的频道名称是否在表中
//        根据名称查询
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmChannel::getName,wmChannel.getName());

        WmChannel one = this.getOne(queryWrapper);
        if(one!=null){ //代表 表中已经存在这个频道
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }

        try {
            this.save(wmChannel);
        } catch (Exception e) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        return ResponseResult.okResult();
    }
}
